<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>苏北·矩阵禁玩系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        matrix: '#00FF41',    // 黑客帝国绿
                        matrix-dark: '#002B00',// 深绿底
                        matrix-light: '#00FF80',// 亮绿高亮
                        danger: '#FF4141',
                        success: '#00FF41',
                    },
                    fontFamily: {
                        matrix: ['"Courier New"', 'monospace', 'system-ui'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            /* 矩阵数字雨背景 */
            .matrix-rain {
                position: fixed; top: 0; left: 0;
                width: 100%; height: 100%;
                z-index: -1; opacity: 0.25;
                pointer-events: none;
            }
            /* 矩阵卡片样式 */
            .matrix-card {
                background-color: rgba(0,43,0,0.85);
                border: 1px solid #00FF41;
                box-shadow: 0 10px 30px -5px rgba(0,255,65,0.2);
            }
            .hover-lift {
                transition: transform 0.3s ease, box-shadow 0.3s ease;
            }
            .hover-lift:hover {
                transform: translateY(-5px);
                box-shadow: 0 15px 35px -5px rgba(0,255,65,0.3);
            }
            /* 矩阵输入框/按钮样式 */
            .matrix-input {
                background-color: rgba(0,43,0,0.7);
                border: 1px solid #00FF41;
                color: #00FF41;
                font-family: 'Courier New', monospace;
            }
            .matrix-input:focus {
                border-color: #00FF80;
                box-shadow: 0 0 5px rgba(0,255,65,0.5);
                outline: none;
            }
            .matrix-btn {
                background-color: #00FF41;
                color: #002B00;
                font-weight: bold;
                border: 1px solid #00FF41;
                transition: all 0.2s ease;
            }
            .matrix-btn:hover {
                background-color: #00FF80;
                box-shadow: 0 0 8px rgba(0,255,65,0.5);
            }
            .matrix-btn-danger {
                background-color: #FF4141;
                color: #002B00;
                font-weight: bold;
                border: 1px solid #FF4141;
                transition: all 0.2s ease;
            }
            .matrix-btn-danger:hover {
                background-color: #FF6161;
                box-shadow: 0 0 8px rgba(255,65,65,0.5);
            }
            .matrix-btn-success {
                background-color: #00FF41;
                color: #002B00;
                font-weight: bold;
                border: 1px solid #00FF41;
                transition: all 0.2s ease;
            }
            .matrix-btn-success:hover {
                background-color: #00FF80;
                box-shadow: 0 0 8px rgba(0,255,65,0.5);
            }
            /* 矩阵文字闪烁效果 */
            .matrix-blink {
                animation: blink 1.2s infinite;
            }
            @keyframes blink {
                0%,100% { opacity: 1; }
                50% { opacity: 0.6; }
            }
        }
    </style>
</head>
<body class="bg-black text-matrix font-matrix min-h-screen overflow-x-hidden">
    <!-- 矩阵数字雨背景 -->
    <canvas id="matrixRain" class="matrix-rain"></canvas>

    <header class="sticky top-0 z-40 bg-matrix-dark border-b border-matrix/60 shadow-md">
        <div class="container mx-auto px-4 py-5">
            <!-- 苏北品牌标题 -->
            <div class="flex justify-center mb-5">
                <h1 class="text-2xl font-bold flex items-center matrix-blink">
                    <<i class="fa fa-terminal mr-3"></</i>苏北·矩阵禁玩系统
                </h1>
            </div>
            <!-- 参数输入区 -->
            <div class="max-w-2xl mx-auto">
                <div class="relative mb-3">
                    <textarea 
                        id="params-input" 
                        placeholder="PASTE TOKEN & OPENID [SYNTAX: access_token=xxx&openid=xxx]" 
                        class="matrix-input w-full px-4 py-3 rounded resize-none"
                        rows="4"
                    ></textarea>
                    <div class="absolute right-3 top-3 text-gray-400 text-xs">
                        <<i class="fa fa-info-circle" title="AUTO PARSE PARAMS"></</i>
                    </div>
                </div>
                <!-- 功能按钮组 -->
                <div class="flex flex-wrap gap-3 justify-end">
                    <button id="query-btn" class="matrix-btn px-6 py-2 rounded flex items-center">
                        <<i class="fa fa-search mr-2"></</i>查询游戏
                    </button>
                    <button id="clear-btn" class="matrix-input px-4 py-2 rounded flex items-center">
                        <<i class="fa fa-eraser mr-1"></</i>CLEAR
                    </button>
                    <button id="refresh-btn" class="matrix-input px-4 py-2 rounded flex items-center">
                        <<i class="fa fa-refresh mr-1"></</i>RESET
                    </button>
                </div>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-6 max-w-4xl">
        <!-- 系统提示 -->
        <div class="text-center mb-8">
            <h2 class="text-xl font-semibold mb-2">游戏限制状态 [苏北矩阵]</h2>
            <p class="text-gray-400 text-xs max-w-2xl mx-auto">
                仅显示和平精英数据 | 部分限制解除需10-15分钟，部分秒解
            </p>
        </div>

        <!-- 批量操作按钮 -->
        <div class="flex flex-wrap gap-4 justify-center mb-8">
            <button id="batch-ban-btn" class="matrix-btn-danger px-8 py-3 rounded-lg flex items-center disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                <<i class="fa fa-ban mr-2"></</i>
                <span class="button-text">一键禁玩</span>
                <span class="loading-indicator hidden ml-2"><<i class="fa fa-spinner fa-spin"></</i></span>
            </button>
            <button id="batch-unban-btn" class="matrix-btn-success px-8 py-3 rounded-lg flex items-center disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                <<i class="fa fa-check-circle mr-2"></</i>
                <span class="button-text">一键解除禁玩</span>
                <span class="loading-indicator hidden ml-2"><<i class="fa fa-spinner fa-spin"></</i></span>
            </button>
        </div>

        <!-- 游戏列表容器 -->
        <div id="games-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        </div>

        <!-- 状态提示 -->
        <div id="loading" class="flex justify-center items-center py-16">
            <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-matrix"></div>
        </div>
        <div id="no-data" class="text-center py-16 hidden">
            <<i class="fa fa-database text-5xl text-gray-600 mb-4"></</i>
            <p class="text-gray-600 text-sm">游戏数据未找到 [苏北矩阵]</p>
        </div>
        <div id="error-message" class="text-center py-16 hidden">
            <<i class="fa fa-exclamation-triangle text-5xl text-red-500 mb-4"></</i>
            <p class="text-red-500 text-sm" id="error-text">系统错误 [苏北矩阵]</p>
        </div>
        <div id="param-error" class="text-center py-16 hidden">
            <<i class="fa fa-exclamation-triangle text-yellow-500 text-5xl mb-4"></</i>
            <p class="text-yellow-500 text-lg" id="param-error-text">未找到有效参数 [苏北矩阵]</p>
        </div>
    </main>

    <div id="toast" class="fixed bottom-6 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-lg shadow-lg text-white hidden z-50"></div>

    <footer class="bg-matrix-dark border-t border-matrix/40 py-4 mt-12">
        <div class="container mx-auto px-4 text-center text-gray-600 text-xs">
            <p>苏北·矩阵禁玩系统 v1.0 | 仅供测试使用 | © 2025</p>
        </div>
    </footer>

    <script>
        // 矩阵数字雨效果
        const canvas = document.getElementById('matrixRain');
        const ctx = canvas.getContext('2d');
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        const chars = '01ABCDEFGHIJKLMNOPQRSTUVWXYZアイウエオカキクケコサシスセソ';
        const columns = Math.floor(canvas.width / 18);
        const drops = Array(columns).fill(1);

        function drawMatrixRain() {
            ctx.fillStyle = 'rgba(0,0,0,0.05)';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            ctx.fillStyle = '#00FF41';
            ctx.font = '18px Courier New';

            drops.forEach((y, col) => {
                const char = chars[Math.floor(Math.random() * chars.length)];
                ctx.fillText(char, col * 18, y * 18);
                
                if (y * 18 > canvas.height && Math.random() > 0.975) {
                    drops[col] = 0;
                }
                drops[col]++;
            });
        }
        setInterval(drawMatrixRain, 35);

        // 核心功能逻辑（原功能完全保留）
        const gamesContainer = document.getElementById('games-container');
        const loadingIndicator = document.getElementById('loading');
        const noDataIndicator = document.getElementById('no-data');
        const errorMessage = document.getElementById('error-message');
        const errorText = document.getElementById('error-text');
        const paramError = document.getElementById('param-error');
        const paramErrorText = document.getElementById('param-error-text');
        const refreshBtn = document.getElementById('refresh-btn');
        const queryBtn = document.getElementById('query-btn');
        const clearBtn = document.getElementById('clear-btn');
        const paramsInput = document.getElementById('params-input');
        const toast = document.getElementById('toast');
        const batchBanBtn = document.getElementById('batch-ban-btn');
        const batchUnbanBtn = document.getElementById('batch-unban-btn');

        let customParams = {
            access_token: '',
            openid: ''
        };
        let currentGames = [];

        function showToast(message, isError = false) {
            toast.textContent = message;
            toast.className = `fixed bottom-6 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-lg shadow-lg text-white z-50 ${
                isError ? 'bg-red-900/80 text-red-400 border border-red-600' : 'bg-matrix-dark text-matrix border border-matrix'
            }`;
            toast.classList.remove('hidden');
            
            setTimeout(() => {
                toast.classList.add('hidden');
            }, 3000);
        }

        function parseParams(input) {
            const params = {
                access_token: '',
                openid: ''
            };
            
            if (!input.trim()) return params;
            
            const patterns = {
                access_token: [
                    /access_token=([^&\s"']+)/i,
                    /access_token\s*:\s*"([^"]+)"/i,
                    /access_token\s*=\s*'([^']+)'/i
                ],
                openid: [
                    /openid=([^&\s"']+)/i,
                    /openid\s*:\s*"([^"]+)"/i,
                    /openid\s*=\s*'([^']+)'/i
                ]
            };
            
            for (const pattern of patterns.access_token) {
                const match = input.match(pattern);
                if (match && match[1]) {
                    params.access_token = match[1].trim();
                    break;
                }
            }
            
            for (const pattern of patterns.openid) {
                const match = input.match(pattern);
                if (match && match[1]) {
                    params.openid = match[1].trim();
                    break;
                }
            }
            
            if (!params.access_token || !params.openid) {
                const pipeSeparatedMatch = input.match(/([A-F0-9]+)\|([A-F0-9]+)\|([A-F0-9]+)\|\d+\|\d+/);
                if (pipeSeparatedMatch) {
                    if (!params.openid) {
                        params.openid = pipeSeparatedMatch[1];
                    }
                    if (!params.access_token) {
                        params.access_token = pipeSeparatedMatch[2];
                    }
                }
            }
            
            return params;
        }

        function formatDuration(seconds) {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            return `${hours}小时${minutes}分钟`;
        }

        async function fetchGameData() {
            try {
                loadingIndicator.classList.remove('hidden');
                gamesContainer.classList.add('hidden');
                noDataIndicator.classList.add('hidden');
                errorMessage.classList.add('hidden');
                paramError.classList.add('hidden');
                setBatchButtonsState(false);

                if (!customParams.access_token || !customParams.openid) {
                    loadingIndicator.classList.add('hidden');
                    paramError.classList.remove('hidden');
                    paramErrorText.textContent = '无法提取有效参数，请检查输入';
                    return;
                }

                const params = [];
                if (customParams.access_token) params.push(`access_token=${encodeURIComponent(customParams.access_token)}`);
                if (customParams.openid) params.push(`openid=${encodeURIComponent(customParams.openid)}`);
                const queryString = `?${params.join('&')}`;

                const response = await fetch(`api.php${queryString}`);
                
                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                const gameData = await response.json();
                
                loadingIndicator.classList.add('hidden');
                
                if (gameData.playGames && gameData.playGames.length > 0) {
                    currentGames = gameData.playGames;
                    gamesContainer.classList.remove('hidden');
                    renderGameCards(currentGames);
                    setBatchButtonsState(true);
                } else {
                    currentGames = [];
                    noDataIndicator.classList.remove('hidden');
                    setBatchButtonsState(false);
                }
                
            } catch (error) {
                loadingIndicator.classList.add('hidden');
                errorMessage.classList.remove('hidden');
                errorText.textContent = `数据加载失败`;
                console.error('获取游戏数据时出错:', error);
                setBatchButtonsState(false);
            }
        }

        function renderGameCards(games) {
            gamesContainer.innerHTML = '';
            
            games.forEach(game => {
                const card = document.createElement('div');
                card.className = 'matrix-card rounded-xl overflow-hidden hover-lift';
                
                const statusClass = game.hasBan 
                    ? 'bg-danger text-white' 
                    : 'bg-success text-white';
                const statusText = game.hasBan ? '已禁止' : '可游玩';
                
                let gameIcon = game.gameIcon;
                if (gameIcon.startsWith('//')) {
                    gameIcon = 'https:' + gameIcon;
                }
                
                card.innerHTML = `
                    <div class="relative">
                        <img src="${gameIcon}" alt="${game.gameName}图标" 
                             class="w-full h-48 object-cover">
                        <div class="absolute top-3 right-3 px-3 py-1 rounded-full text-sm font-medium ${statusClass}">
                            ${statusText}
                        </div>
                    </div>
                    <div class="p-5">
                        <h3 class="text-xl font-bold text-matrix mb-2">${game.gameName}</h3>
                        <div class="space-y-2 text-gray-400">
                            <p><<i class="fa fa-id-card-o mr-2"></</i>游戏ID: ${game.gameId}</p>
                            <p><<i class="fa fa-clock-o mr-2"></</i>累计时长: ${formatDuration(game.playDuration)}</p>
                            <p><<i class="fa fa-rmb mr-2"></</i>累计消费: ¥${game.payAmount}</p>
                        </div>
                        <div class="mt-4 pt-4 border-t border-matrix/30">
                            <button class="w-full py-2 px-4 rounded-lg border ${game.hasBan ? 'border-success text-success hover:bg-success hover:text-white' : 'border-danger text-danger hover:bg-danger hover:text-white'} transition-colors duration-300"
                                    onclick="toggleBanStatus(${game.gameId}, ${!game.hasBan}, this)">
                                <span class="loading-indicator hidden"><<i class="fa fa-spinner fa-spin mr-1"></</i>处理中...</span>
                                <span class="button-text">${game.hasBan ? '解除禁止' : '禁止游戏'}</span>
                            </button>
                        </div>
                    </div>
                `;
                
                gamesContainer.appendChild(card);
            });
        }

        async function toggleBanStatus(gameId, newStatus, buttonElement) {
            try {
                const loadingIndicator = buttonElement.querySelector('.loading-indicator');
                const buttonText = buttonElement.querySelector('.button-text');
                loadingIndicator.classList.remove('hidden');
                buttonText.classList.add('hidden');
                buttonElement.disabled = true;

                if (!customParams.access_token || !customParams.openid) {
                    showToast('参数无效，请重新查询', true);
                    loadingIndicator.classList.add('hidden');
                    buttonText.classList.remove('hidden');
                    buttonElement.disabled = false;
                    return;
                }

                const params = [];
                if (customParams.access_token) params.push(`access_token=${encodeURIComponent(customParams.access_token)}`);
                if (customParams.openid) params.push(`openid=${encodeURIComponent(customParams.openid)}`);
                const queryString = `?${params.join('&')}`;

                const requestData = {
                    gameId: gameId,
                    banStatus: newStatus
                };

                let responses;
                if (!newStatus) {
                    const response1 = await fetch(`api.php${queryString}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(requestData)
                    });
                    
                    await new Promise(resolve => setTimeout(resolve, 100));
                    
                    const response2 = await fetch(`api.php${queryString}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(requestData)
                    });
                    
                    responses = [await response1.json(), await response2.json()];
                } else {
                    const response = await fetch(`api.php${queryString}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(requestData)
                    });
                    responses = [await response.json()];
                }

                const allSuccess = responses.every(res => res.success);
                
                if (allSuccess) {
                    showToast(responses[0].message || '操作成功');
                    fetchGameData();
                } else {
                    showToast(responses.find(res => !res.success).error || '操作失败', true);
                    loadingIndicator.classList.add('hidden');
                    buttonText.classList.remove('hidden');
                    buttonElement.disabled = false;
                }
            } catch (error) {
                showToast(`操作失败: ${error.message}`, true);
                console.error('切换游戏状态时出错:', error);
                
                const loadingIndicator = buttonElement.querySelector('.loading-indicator');
                const buttonText = buttonElement.querySelector('.button-text');
                loadingIndicator.classList.add('hidden');
                buttonText.classList.remove('hidden');
                buttonElement.disabled = false;
            }
        }

        async function batchOperation(banAll) {
            if (currentGames.length === 0) {
                showToast('没有可操作的游戏数据', true);
                return;
            }
            
            if (!customParams.access_token || !customParams.openid) {
                showToast('参数无效，请重新查询', true);
                return;
            }
            
            const btn = banAll ? batchBanBtn : batchUnbanBtn;
            const loadingIndicator = btn.querySelector('.loading-indicator');
            const buttonText = btn.querySelector('.button-text');
            loadingIndicator.classList.remove('hidden');
            buttonText.classList.add('hidden');
            setBatchButtonsState(false);
            
            try {
                const params = [];
                if (customParams.access_token) params.push(`access_token=${encodeURIComponent(customParams.access_token)}`);
                if (customParams.openid) params.push(`openid=${encodeURIComponent(customParams.openid)}`);
                const queryString = `?${params.join('&')}`;
                
                const gameIds = banAll 
                    ? currentGames.filter(game => !game.hasBan).map(game => game.gameId)
                    : currentGames.map(game => game.gameId);
                
                if (banAll && gameIds.length === 0) {
                    showToast('所有游戏都已禁止');
                    loadingIndicator.classList.add('hidden');
                    buttonText.classList.remove('hidden');
                    setBatchButtonsState(true);
                    return;
                }
                
                showToast(`正在${banAll ? '禁止' : '解除禁止'}${gameIds.length}个游戏...`);
                
                const results = [];
                for (const gameId of gameIds) {
                    const requestData = {
                        gameId: gameId,
                        banStatus: banAll
                    };
                    
                    if (!banAll) {
                        try {
                            const response1 = await fetch(`api.php${queryString}`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(requestData)
                            });
                            results.push(await response1.json());
                        } catch (error) {
                            results.push({ success: false, error: `请求失败: ${error.message}` });
                        }
                        
                        await new Promise(resolve => setTimeout(resolve, 100));
                        
                        try {
                            const response2 = await fetch(`api.php${queryString}`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(requestData)
                            });
                            results.push(await response2.json());
                        } catch (error) {
                            results.push({ success: false, error: `第二次请求失败: ${error.message}` });
                        }
                    } else {
                        try {
                            const response = await fetch(`api.php${queryString}`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(requestData)
                            });
                            results.push(await response.json());
                        } catch (error) {
                            results.push({ success: false, error: `请求失败: ${error.message}` });
                        }
                    }
                    
                    await new Promise(resolve => setTimeout(resolve, 200));
                }
                
                const allSuccess = results.every(res => res.success);
                const failedCount = results.filter(res => !res.success).length;
                
                if (allSuccess) {
                    showToast(banAll ? '所有游戏已成功禁止' : '所有游戏已成功解除禁止');
                } else {
                    showToast(`${banAll ? '禁止' : '解除禁止'}完成，${failedCount}个游戏操作未成功`, true);
                }
                
                fetchGameData();
                
            } catch (error) {
                showToast(`批量操作失败: ${error.message}`, true);
                console.error('批量操作时出错:', error);
                
                loadingIndicator.classList.add('hidden');
                buttonText.classList.remove('hidden');
                setBatchButtonsState(true);
            }
        }

        function setBatchButtonsState(enabled) {
            batchBanBtn.disabled = !enabled;
            batchUnbanBtn.disabled = !enabled;
        }

        queryBtn.addEventListener('click', () => {
            const inputValue = paramsInput.value;
            customParams = parseParams(inputValue);
            
            if (customParams.access_token && customParams.openid) {
                fetchGameData();
                showToast('参数提取成功，正在查询数据...');
            } else {
                showToast('无法提取有效参数', true);
                paramError.classList.remove('hidden');
                setBatchButtonsState(false);
            }
        });

        refreshBtn.addEventListener('click', () => {
            if (!customParams.access_token || !customParams.openid) {
                showToast('请先输入并查询有效参数', true);
                return;
            }
            
            fetchGameData();
            showToast('正在刷新数据...');
        });

        clearBtn.addEventListener('click', () => {
            paramsInput.value = '';
            customParams = { access_token: '', openid: '' };
            currentGames = [];
            showToast('已清空输入内容');
            
            gamesContainer.classList.add('hidden');
            noDataIndicator.classList.add('hidden');
            errorMessage.classList.add('hidden');
            paramError.classList.add('hidden');
            setBatchButtonsState(false);
        });

        batchBanBtn.addEventListener('click', () => batchOperation(true));
        batchUnbanBtn.addEventListener('click', () => batchOperation(false));

        paramsInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                queryBtn.click();
            }
        });

        document.addEventListener('DOMContentLoaded', () => {
            setBatchButtonsState(false);
        });
    </script>
</body>
</html>
